package com.yxsk.relay.job.admin.core.router.selector;

import com.yxsk.relay.job.admin.core.router.Router;
import com.yxsk.relay.job.admin.core.schedule.quartz.vo.JobConfig;
import com.yxsk.relay.job.admin.exception.route.RelayRouteException;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

/**
 * @Author 11376
 * @CreaTime 2019/6/15 13:06
 * @Description 决策链路由决策者
 */
public class ChainRouterDecisionMaker implements RouterDecisionMaker {

    private List<RouteSelector> selectors = Collections.synchronizedList(new ArrayList<>());

    public ChainRouterDecisionMaker() {
        this(null);
    }

    public ChainRouterDecisionMaker(List<RouteSelector> selectors) {
        if (!CollectionUtils.isEmpty(selectors)) {
            this.selectors.addAll(selectors);
        }
    }

    public void addSelector(RouteSelector selector) {
        this.selectors.add(selector);
    }

    @Override
    public Router decision(JobConfig jobConfig) {
        // 实例化 chain
        SelectorChain chain = new SelectorChain();
        chain.iterator = this.selectors.iterator();
        Router router = chain.chain(jobConfig);
        if (router == null) {
            throw new RelayRouteException("Not found router, job config: " + jobConfig);
        }
        return router;
    }

    private class SelectorChain implements RouteSelector.Chain {

        Iterator<RouteSelector> iterator;

        @Override
        public Router chain(JobConfig jobConfig) {
            if (iterator.hasNext()) {
                return iterator.next().select(jobConfig, this);
            }
            return null;
        }

    }

}
